<?php


namespace App\Http\Controllers\Admin\User;


use App\Exceptions\LogicException;
use App\Http\Controllers\Controller;
use App\Models\Adminer\RoleMenu;
use App\Models\Adminer\Menus;
use App\Utils\ResUtil;
use App\Models\Adminer\Role;
use App\Services\ValidatorService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class PermissionController extends Controller
{
    public function roleList()
    {
        $name = request()->get('name', '');
        $models = Role::getByStoreId($name, 'id', 'name', 'remark', 'enable');
        $list = [];
        foreach($models as $k => $model) {
            $list[$k] = $model->label()->toArray();
        }
        return $this->ok(compact('list'));
    }

    public function menusList()
    {
        $role_id = request()->get('role_id', '');
        $list = Menus::getMenusByRoleId($role_id);
        return $this->ok(compact('list'));
    }

    public function editRole()
    {
        $data = request()->json()->all();
        if(isset($data['id'])) {
            $role = Role::find($data['id']);
        } else {
            $role = new Role();
        }

        $na = Role::getByName($data['name']);
        if($na && ($na->id ?? '') !== ($role->id ?? '')) {
            throw new LogicException('角色名不能重复');
        }

        $role->fill([
            'remark' => $data['remark'] ?? '', // 说明
            'enable' => $data['enable'] ?? 1, //
            'name' => $data['name'] ?? ''
        ]);

        $role->save();
        RoleMenu::where('role_id', $role->id)->delete();
        foreach((array) $data['menu_ids'] as $menu_id) {
            RoleMenu::create([
                'role_id' => $role->id, // 角色ID
                'menu_id' => $menu_id, // 菜单ID
            ]);
        }
        return $this->ok();
    }
}
